
package com.itboy.pay.alipay.controller;

import com.itboy.common.annotation.Log;
import com.itboy.common.annotation.RepeatSubmit;
import com.itboy.common.core.controller.BaseController;
import com.itboy.common.core.domain.AjaxResult;
import com.itboy.common.enums.BusinessType;
import com.itboy.pay.alipay.domain.PayAlipayConfig;
import com.itboy.pay.alipay.service.AliPayService;
import com.itboy.pay.alipay.utils.AliPayStatusEnum;
import com.itboy.pay.alipay.utils.AlipayUtils;
import com.itboy.pay.alipay.vo.TradeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author gssong
 * @date2021/07/11
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/pay/aliPay")
@Api(tags = "工具：支付宝管理")
public class AliPayController extends BaseController {

    private final AlipayUtils alipayUtils;
    private final AliPayService alipayService;

    @GetMapping
    public AjaxResult<PayAlipayConfig> queryConfig() {
		return AjaxResult.success(alipayService.getById(1));
    }

	@Log(title = "配置支付宝", businessType = BusinessType.UPDATE)
    @ApiOperation("配置支付宝")
    @PutMapping
	public AjaxResult<Void> edit(@RequestBody PayAlipayConfig alipayConfig) {
		return toAjax(alipayService.updateById(alipayConfig) ? 1 : 0);
	}

	@Log(title = "支付宝PC网页支付", businessType = BusinessType.INSERT)
    @ApiOperation("PC网页支付")
	@RepeatSubmit
    @PostMapping(value = "/toPayAsPC")
    public AjaxResult toPayAsPc(@Validated @RequestBody TradeVo trade) throws Exception {
        PayAlipayConfig aliPay = alipayService.getById(1);
        trade.setOutTradeNo(alipayUtils.getOrderCode());
        String payUrl = alipayService.toPayAsPc(aliPay, trade);
		return AjaxResult.success("操作成功",payUrl);
    }

	@Log(title = "支付宝手机网页支付", businessType = BusinessType.INSERT)
    @ApiOperation("手机网页支付")
	@RepeatSubmit
    @PostMapping(value = "/toPayAsWeb")
    public AjaxResult toPayAsWeb(@Validated @RequestBody TradeVo trade) throws Exception {
        PayAlipayConfig alipay = alipayService.getById(1);
        trade.setOutTradeNo(alipayUtils.getOrderCode());
        String payUrl = alipayService.toPayAsWeb(alipay, trade);
        return AjaxResult.success("操作成功",payUrl);
    }

    @ApiIgnore
    @RequestMapping("/return")
    @ApiOperation("支付之后跳转的链接")
    public AjaxResult<Void> returnPage(HttpServletRequest request, HttpServletResponse response) {
        PayAlipayConfig alipay = alipayService.getById(1);
        response.setContentType("text/html;charset=" + alipay.getCharset());
        //内容验签，防止黑客篡改参数
        if (alipayUtils.rsaCheck(request, alipay)) {
            //商户订单号
            String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //支付宝交易号
            String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println("商户订单号" + outTradeNo + "  " + "第三方交易号" + tradeNo);

            // 根据业务需要返回数据，这里统一返回OK
            return AjaxResult.success("payment successful");
        } else {
            // 根据业务需要返回数据
            return AjaxResult.error();
        }
    }

    @ApiIgnore
    @RequestMapping("/notify")
    @ApiOperation("支付异步通知(要公网访问)，接收异步通知，检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致，根据trade_status进行后续业务处理")
    public AjaxResult<Void> notify(HttpServletRequest request) {
        PayAlipayConfig alipay = alipayService.getById(1);
        Map<String, String[]> parameterMap = request.getParameterMap();
        //内容验签，防止黑客篡改参数
        if (alipayUtils.rsaCheck(request, alipay)) {
            //交易状态
            String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 商户订单号
            String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //支付宝交易号
            String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //付款金额
            String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //验证
            if (tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue()) || tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())) {
                // 验证通过后应该根据业务需要处理订单
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
}
